import React, { useEffect, useState } from 'react'
import { Layout, Menu } from 'antd';
import { withRouter } from 'react-router-dom/cjs/react-router-dom.min';
import axios from 'axios';
import { connect } from 'react-redux';

function SideMenu(props) {
  // const [collapsed, setCollapsed] = useState(false);
  const [menu, setMenu] = useState([])
  const right = JSON.parse(localStorage.getItem('token')).role.rights
  const { Sider } = Layout;


  function getItem(label, key, children) {
    return {
      key,
      children,
      label,
    };
  }

  useEffect(() => {

    axios.get('/rights?_embed=children').then(res => {
      // console.log(res.data)
      setMenu(res.data)
    })
  }, [])

  // 遍历菜单
  const mapList = (list) => {
    // console.log(right)
    // console.log(list)
    const arr = []
    list.map((item) => {
      // console.log(item)
      if (item.children && item.children.length !== 0) {
        return arr.push(getItem(item.title, item.key, mapList(item.children)))
      } else {
        // console.log(item)
        return item.pagepermisson && right.includes(item.key) && arr.push(getItem(item.title, item.key))
      }
    })
    // console.log(arr)
    return arr
  }
  const openK = '/' + props.location.pathname.split('/')[1]

  return (
    <Sider trigger={null} collapsible collapsed={props.isCollapsed}>
      <div style={{ display: 'flex', height: '100%', flexDirection: "column" }}>
        <div className="demo-logo-vertical" style={{ color: 'white', textAlign: 'center', fontSize: '18px', margin: '10px' }} >全球新闻发布系统</div>
        <div style={{ flex: '1', overflow: 'auto' }}>
          <Menu
            theme="dark"
            mode="inline"
            selectedKeys={[props.location.pathname]}
            items={mapList(menu)}
            onClick={(e) => pushToRoute(e, props)}
            defaultOpenKeys={[openK]}
          />
        </div>
      </div>
    </Sider>
  )
  function pushToRoute(e, props) {
    props.history.push(e.key)
    // console.log(e)
  }
}

const mapStateToProps = ({ CollapsedReducer: { isCollapsed } }) => {
  return {
    isCollapsed
  }
}

export default connect(mapStateToProps)(withRouter(SideMenu))